package com.panlf.springbootdemo.controller;

import com.panlf.springbootdemo.dao.UserDao;
import com.panlf.springbootdemo.entity.UserEntity;
import com.panlf.springbootdemo.service.UserService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Map;

/**
 * @author panlf
 * @since 2024/1/26 14:04
 */
@RequestMapping
@RestController
public class UserController {

    @Resource
    private UserDao userDao;
    @Resource
    private UserService userService;

    // 预期 --> 不回滚
    // 实际 --> 回滚了
    @PostMapping("/add1")
    @Transactional(rollbackFor = Exception.class)
    public String test1() {
        UserEntity userEntity = new UserEntity();
        userEntity.setUsername("张无忌2");
        userEntity.setPassword("123");
        userDao.insert(userEntity);

        throw new RuntimeException("模拟失败");
//        return "ook";
    }

    // 回滚
    @PostMapping("/add2")
    public String test2() {
        UserEntity userEntity = new UserEntity();
        userEntity.setUsername("谢逊");
        userEntity.setPassword("123");
        userService.addAndException(userEntity);

        return "ok";
    }

    @PostMapping("/add3")
    public String test3() {
        UserEntity userEntity = new UserEntity();
        userEntity.setUsername("陈友谅");
        userEntity.setPassword("123");
        userService.add(userEntity);

        return "ok";
    }
}
